package com.mvc.portal.service;

import java.io.File;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.mvc.framework.util.FrameworkContextUtils;
import com.mvc.security.model.User;
import com.mvc.security.service.UserManager;

import freemarker.template.Configuration;

@Service
public class NotificationManager {

	private static final Logger	LOGGER	= Logger.getLogger(NotificationManager.class);

	@Autowired
	private Configuration	    freemarkerConfiguration;

	@Autowired
	private UserManager<User>	userManager;

	@Autowired
	@Qualifier("javaMailSender")
	private JavaMailSenderImpl	mailSender;

	@Value("${send.mail}")
	private Boolean	            sendMail;

	@Value("${mail.dev.alias}")
	private String	            mailDevAlias;

	@Value("${mail.from}")
	private String	            mailFrom;

	@Value("${mail.from.name}")
	private String	            mailFromName;

	@Value("${mail.logo}")
	private String	            mailLogo;

	public void sendTestEmail() {
		this.sendMail("this is a test email", "this a test email content", new File[] { new File(
		        "C:\\Users\\snowpbx\\AppData\\Local\\Temp\\1350207721005.pdf") }, new String[] { "test1.pdf" },
		        new String[] { "snowpbx@gmail.com" }, null, false);
		return;
	}

	public void sendMail(String subject, String content, String to) {
		this.sendMail(subject, content, null, null, new String[] { to }, null, false);
	}

	public void sendMail(String subject, String content, File[] attachments, String[] fileNames, String[] to, String[] cc) {
		sendMail(subject, content, attachments, fileNames, to, cc, false);
	}

	/**
	 * mail sending method for sending mime type email
	 * 
	 * @param subject
	 * @param content
	 * @param to
	 * @throws MessagingException
	 */
	public void sendMail(String subject, String content, File[] attachments, String[] fileNames, String[] to, String[] cc, boolean receipt) {
		try {
			if (sendMail) {
				String alias = mailDevAlias;
				MimeMessage message = mailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
				if (StringUtils.isBlank(alias)) {
					helper.setTo(to);
					if (cc != null && cc.length > 0) {
						helper.setCc(cc);
					}
				} else {
					if (alias.indexOf(",") != -1) {
						helper.setTo(alias.split(","));
					} else {
						helper.setTo(alias);
					}
				}
				InternetAddress from = new InternetAddress();
				from.setAddress(mailFrom);
				from.setPersonal(mailFromName);
				if (fileNames != null) {
					for (int i = 0; i < fileNames.length; i++) {
						helper.addAttachment(fileNames[i], attachments[i]);
					}
				}
				helper.setFrom(from);
				helper.setSubject(subject);
				if (content == null) {
					content = "";
				}
				helper.setText(content, true);

				if (receipt) {
					String notificator = null;
					if (!FrameworkContextUtils.isAdmin()) {
						User sender = userManager.getByObjectId(FrameworkContextUtils.getCurrentUserId());
						if (sender != null) {
							notificator = sender.getEmail();
						}
					}
					if (StringUtils.isBlank(notificator)) {
						notificator = mailFrom;
					}
					message.setHeader("Disposition-Notification-To", notificator);
				}

				mailSender.send(message);

				LOGGER.debug("Subject: " + subject);
				LOGGER.debug("TO: " + StringUtils.join(to, ","));
				LOGGER.debug("Content: " + content);

			} else {
				LOGGER.error("won't send email, because the send.mail=false");
			}
		} catch (Exception e) {
			LOGGER.error("sending email error log", e);
		}
	}

	public String getTemplateString(String template, Map<String, Object> model) {
		try {
			model.put("logo", mailLogo);
			return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(template), model);
		} catch (Exception e) {
			LOGGER.error("getTemplateString", e);
		}
		return "";
	}
}
